import { createStore } from 'redux';

const initialModel = {
  userList: [
    {
      key: '1',
      name: 'John Brown',
      age: 32,
      address: 'New Yorrrk No. 1 Lake Park',
      tags: ['nice', 'developer'],
    },
    {
      key: '2',
      name: 'Jim Green',
      age: 42,
      address: 'London No. 1 Lake Park',
      tags: ['loser'],
    },
    {
      key: '3',
      name: 'Joe Black',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      tags: ['cool', 'teacher'],
    },
  ],
};

export default createStore((model = initialModel, action) => {
  const { userList } = model;

  switch (action.type) {
    case 'create_user':
      const { user } = action.payload;
      return {
        userList: [
          ...userList,
          {
            key: String(userList.length + 1),
            ...user,
          },
        ],
      };
    case 'delete_user':
      const { key } = action.payload;
      return {
        userList: userList.filter((user) => {
          return user.key !== key;
        }),
      };

    case 'update_user':
      const { updatedUser } = action.payload;
      return {
        userList: userList.map((user) => {
          if (user.key !== updatedUser.key) {
            return user;
          }
          return updatedUser;
        }),
      };
    default:
      return model;
  }
});
